package com.cloud.io;

import java.io.ByteArrayInputStream;

/**
 * ByteArrayInputStream测试
 * 数组中写入或读出byte型数据
 */
public class ByteArrayStreamTest {

    private static final int LEN = 5;

    // 对应abcddefghijklmnopqrsttuvwxyz的ASCII码
    private static final byte[] arrayLetters = {
            0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
            0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
    };

    private static void testByteArrayInputStream() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(arrayLetters);

        //读取5个字节
        for(int i = 0; i < LEN; i++) {
            //如果还可以继续读取
            if(byteArrayInputStream.available() >= 0) {
                //读取下一个字节并打印
                int temp = byteArrayInputStream.read();
                System.out.printf("%d : 0x%s\n", i, Integer.toHexString(temp));
            }
        }
        //如果不支持mark功能
        if(!byteArrayInputStream.markSupported()) {
            System.out.println("Make not supported!");
        }

        //标记当前位置，一旦调用reset()方法，会重置到标记位置
        //mark方法的参数0其实没有实际意义
        byteArrayInputStream.mark(0);
        //跳过5个字节
        byteArrayInputStream.skip(5);
        //读取5个字节
        byte[] buf = new byte[LEN];
        byteArrayInputStream.read(buf, 0, LEN);
        String str1 = new String(buf);
        System.out.printf("str1=%s\n", str1);

        //重置回标记位置
        byteArrayInputStream.reset();
        byteArrayInputStream.read(buf, 0, LEN);
        String str2 = new String(buf);
        System.out.printf("str2=%s\n", str2);
    }

    public static void main(String[] args) {
        testByteArrayInputStream();
    }
}
